from entity import Event
import json
from util import mapping, jformat
from models import db
from services import service_old


def userInfo():
    return json.dumps({
        "avatar": "https://randy168.com/1533262153771.gif",
        "name": "event",
        "roles": ["event"],
        "data": ["index", "order-manage", "order-list", "product-manage", "product-list", "review-manage",
                 "return-goods","camera",
                 "goods", "goods-list", "goods-classify", "permission", "user-manage", "role-manage", "menu-manage"]
    })


def getAll():
    events = Event.query.all()
    print(events)
    eventList = []
    for event in events:
        eventList.append(mapping.eventToDict(event, service_old.getNameById(event.oldperson_id)))
    print(eventList)
    return json.dumps(eventList)


def getById(id):
    # 通过id搜索数据库
    one = Event.query.get(id)
    event = mapping.eventToDict(one)
    return json.dumps([event])


def update(request_data):
    # 是否存在
    if db.session.query(Event).filter(Event.ID == request_data['ID']).count() != 0:
        db.session.query(Event).filter(Event.ID == request_data['ID']).update(request_data)
        db.session.commit()
        return 'ok'
    else:
        return 'error'


def add(request_data):
    print(request_data)
    if(request_data == None):
        return 'null'
    db.session.execute(
        Event.__table__.insert(),
        request_data
    )
    db.session.commit()
    return 'ok'


def deleteByID(ID):
    Event.query.filter(Event.ID == ID).delete()
    # 提交会话
    db.session.commit()
    return 'del'


def initEvent(data):
    event = Event()
    for item in dir(event):
        if item.startswith('_'):
            continue
        print(item)
        if item in data.keys():
            event.__setattr__(item, data[item])
            print(data[item])
    return event
